package com.security.securityproject.exception;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author huangkf
 * @version 1.0
 * @date 2022/12/4 : 21:06
 * @description 没有权限配置类，增加用户体验
 */


@Component  //将权限不足的实体注入到spring容器
public class MyExceptionAcessDenidHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //异步响应，需要处理乱码
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);//响应状态码为禁止，否则返回的状态码为200,不符合业务要求
        response.setHeader("Content-Type","application/json;charset=UTF-8");//设置响应时候的编码
        PrintWriter writer = response.getWriter();  //设置响应时候的流
        writer.write("{\"status\":\"error\",\"msg\":\"权限不足，请联系管理员！\"}"); //将数据输出到页面
        writer.flush(); //刷新流
        writer.close();//关闭流


    }
}
